package com.yc.storage.service.impl;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.sms.SmsManager;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.yc.storage.service.IQiniuService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class QiniuServiceImpl implements IQiniuService, InitializingBean {

    private final UploadManager uploadManager;
    private final BucketManager bucketManager;
    private final Auth auth;

    @Value("${qiniu.bucket}")
    private String bucket;

    @Value("${qiniu.captchaMsgTemplateId}")
    private String captchaMsgTemplateId;

    /**
     * 定义七牛云上传的相关策略
     */
    private StringMap putPolicy;

    @Override
    public boolean uploadFile(File file, String fileName) throws QiniuException {
        Response response = this.uploadManager.put(file, fileName, getUploadToken());
        int retry = 0;
        while (response.needRetry() && retry < 3) {
            response = this.uploadManager.put(file, fileName, getUploadToken());
            retry++;
        }
        return response.statusCode == 200;
    }

    @Override
    public boolean uploadFile(InputStream inputStream, String fileName) throws QiniuException {
        Response response = this.uploadManager.put(inputStream, fileName, getUploadToken(), null, null);
        int retry = 0;
        while (response.needRetry() && retry < 3) {
            response = this.uploadManager.put(inputStream, fileName, getUploadToken(), null, null);
            retry++;
        }
        return response.statusCode == 200;
    }


    @Override
    public boolean delete(String key) throws QiniuException {
        Response response = bucketManager.delete(this.bucket, key);
        int retry = 0;
        while (response.needRetry() && retry++ < 3) {
            response = bucketManager.delete(bucket, key);
        }
        return response.statusCode == 200;
    }

    @Override
    public boolean moveFile(String fromKey, String toKey) throws QiniuException {
        Response response = bucketManager.move(this.bucket, fromKey, this.bucket, toKey, true);
        int retry = 0;
        while (response.needRetry() && retry++ < 3) {
            response = bucketManager.move(this.bucket, fromKey, this.bucket, toKey, true);
        }
        return response.statusCode == 200;
    }

    @Override
    public boolean sendCaptchaMessage(String[] phones, String captcha) {
        SmsManager smsManager = new SmsManager(this.auth);
        Map<String, String> map = new HashMap<>();
        map.put("code", captcha);
        try {
            Response response = smsManager.sendMessage(captchaMsgTemplateId, phones, map);
            int retry = 0;
            while (response.needRetry() && retry++ < 3) {
                response = smsManager.sendMessage(captchaMsgTemplateId, phones, map);
            }
            return response.statusCode == 200;
        } catch (QiniuException e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public void afterPropertiesSet() {
        this.putPolicy = new StringMap();
        putPolicy.put("returnBody", "{\"key\":\"$(key)\",\"hash\":\"$(etag)\",\"ext\":\"$(ext)\",\"fsize\":\"$(fsize)\",\"fname\":\"$(fname)\",\"bucket\":\"$(bucket)\",\"width\":$(imageInfo.width), \"height\":${imageInfo.height}}");
    }

    /**
     * 获取上传凭证
     */
    @Override
    public String getUploadToken() {
        return this.auth.uploadToken(bucket, null, 3600, putPolicy);
    }
}
